import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UseInterceptors,
  ParseIntPipe,
  VERSION_NEUTRAL,
  Version,
  ClassSerializerInterceptor,
  HttpStatus,
  Inject,
  HttpException,
} from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { DemoPipe } from '../utils/demo.pipe';
import { DemoInterceptor } from 'src/utils/demo.interceptor';
import { ApiBody, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { User } from './entities/user.entity';
import { LoginUserDto } from './dto/login.user.dto';
import { RedisService } from 'src/redis/redis.service';

@ApiTags('user')
@Controller({
  path: 'user',
  version: VERSION_NEUTRAL,
})
@UseInterceptors(ClassSerializerInterceptor)
// @UseInterceptors(DemoInterceptor)
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Inject()
  private redisService: RedisService;

  @Post('login')
  async login(@Body() loginUserDto: LoginUserDto) {
    const { email, code } = loginUserDto;
    const codeRedis = await this.redisService.get(`captcha_${email}`);

    if (!codeRedis) {
      throw new HttpException('验证码已过期', HttpStatus.BAD_REQUEST);
    }

    if (code !== codeRedis) {
      // throw new Error('验证码错误');
      throw new HttpException('验证码错误', HttpStatus.BAD_REQUEST);
    }
    // const user = await this.userService.findOne({ email });
    const user = await this.userService.findUserByEmail(email);
    console.log(user);
    return 'success';
  }

  @Version('2')
  @Get(':id')
  findOneV2(@Param('id', ParseIntPipe) id: number) {
    return 'V2 get one' + id;
  }

  @ApiBody({
    type: CreateUserDto,
  })
  @Post()
  create(@Body(new DemoPipe()) createUserDto: CreateUserDto) {
    // return this.userService.create(createUserDto);
    return 'This action adds a new user' + JSON.stringify(createUserDto);
  }

  @ApiOperation({ summary: 'findAll' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: 'ok',
    type: User,
  })
  @Get()
  findAll() {
    return this.userService.findAll();
  }

  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    return this.userService.findOne(+id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
    return this.userService.update(+id, updateUserDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.userService.remove(+id);
  }
}
